import { Injectable, InternalServerErrorException } from "@nestjs/common";
import { InjectRepository } from "@nestjs/typeorm";
import { getConnection, Repository } from "typeorm";
import {
  AddGoodsDto,
  DelGoodsDto,
  EditGoodsDto,
  GetGoodsByTypeDto,
  GetGoodsDto,
} from "../dto/goods.dto";
import { Goods } from "/@/entities/goods/Goods.entity";
import { GoodsType } from "/@/entities/goods/GoodsType.entity";
import { format } from "/@/utils/moment";
@Injectable()
export class GoodsService {
  constructor(
    @InjectRepository(Goods)
    private goodsRepository: Repository<Goods>,
    @InjectRepository(GoodsType)
    private goodsTypeRepository: Repository<GoodsType>,
  ) {
    //
  }
  /**
   * 获取商品
   * @param params 字段
   */
  async getGoodsList(query: GetGoodsDto) {
    const { pageSize = 20, page = 1, name = "", id, status } = query;
    try {
      let qb = this.goodsRepository.createQueryBuilder("goods");
      qb = qb
        .skip(pageSize * (page - 1))
        .take(pageSize)
        .orderBy("goods.update_at", "DESC") //根据更新时间降序
        .leftJoinAndSelect("goods.goods_types", "goodsType") //左联查询
        .where("goods.name like :name", { name: "%" + name + "%" });
      if (id) {
        qb = qb.andWhere("goods.id = :id", { id });
      }
      if (status) {
        qb = qb.andWhere("goods.status = :status", { status });
      }
      const data = await qb.getManyAndCount();
      const items = data[0].map((item: any) => {
        item.update_at = format(item.update_at, "YYYY-MM-DD HH:mm:ss");
        item.urls = item.urls.split(",");
        return item;
      });
      return { items, total: data[1] };
    } catch (error) {
      throw new InternalServerErrorException("查询失败");
    }
  }

  /**
   * 根据商品类型获取商品
   * @param params 字段
   */
  async getGoodsListByType(query: GetGoodsByTypeDto) {
    const { type_id } = query;
    if (type_id === "0") {
      return [];
    }
    try {
      const result = await this.goodsTypeRepository.findOne(type_id, {
        relations: ["goods"],
      });
      return result.goods;
    } catch (error) {
      throw new InternalServerErrorException("查询失败");
    }
  }

  /**
   * 添加商品
   * @param params 字段
   */
  async addGoods(params: AddGoodsDto) {
    // 商品信息 params
    const { goods_types = [] } = params;
    params.price = params.price * 100;
    delete params.goods_types;
    //新增商品
    try {
      if (goods_types.length !== 0) {
        const connection = getConnection();
        const followList = [];
        for (let i = 0; i < goods_types.length; i++) {
          // 根据商品分类id获取这个商品分类信息 goods
          const goods = await connection.manager.findOne(GoodsType, {
            id: goods_types[i],
          });
          if (!goods) {
            throw new InternalServerErrorException("商品分类操作失败");
          }
          followList.push(goods);
        }
        // 创建商品实体
        const entity = this.goodsRepository.create(params);
        // 关联商品分类信息
        entity.goods_types = followList;
        // 保存商品
        const result = await connection.manager.save(entity);
        if (result) {
          return "商品新增成功";
        }
      }
    } catch (error) {
      console.log(error);
      throw new InternalServerErrorException("添加失败");
    }
  }

  /**
   * 编辑商品
   * @param params 字段
   */
  async editGoods(params: EditGoodsDto) {
    const { goods_types = [], id } = params;
    delete params.goods_types;
    params.price = params.price * 100;
    const data = await this.goodsRepository.findOne({ id });
    if (!data) {
      throw new InternalServerErrorException("查询失败");
    }
    //编辑商品
    try {
      if (goods_types.length !== 0) {
        const connection = getConnection();
        const followList = [];
        for (let i = 0; i < goods_types.length; i++) {
          const goods = await connection.manager.findOne(GoodsType, {
            id: goods_types[i],
          });
          if (!goods) {
            throw new InternalServerErrorException("商品分类操作失败");
          }
          followList.push(goods);
        }
        const entity = this.goodsRepository.create(params);

        entity.goods_types = followList;

        const result = await connection.manager.save(entity);
        if (result) {
          return "商品编辑成功";
        }
      }
    } catch (error) {
      console.log(error);
      throw new InternalServerErrorException("编辑失败");
    }
  }

  /**
   * 删除商品
   * @param params 字段
   */
  async delGoods(params: DelGoodsDto) {
    throw new InternalServerErrorException();
    return params;
  }
}
